const { notify } = require("node-notifier");
const path = require("path");
const { NodeSSH } = require("node-ssh");
const { exec } = require("child_process");
const ssh = new NodeSSH();
const execPromise = (command) => {
    return new Promise((resolve, reject) => {
        exec(command, (err, stdout, stderr) => {
            if (err) {
                reject(err);
            } else {
                resolve({
                    stdout,
                    stderr,
                });
            }
        });
    });
};

async function deployProject() {
    try {
        const start = Date.now();

        var commPath = __dirname.replaceAll("\\部署\\liunx自动部署脚本", "");

        await ssh.connect({
            host: "", //服务器ip
            port: 22,
            username: "root",
            password: "", //ssh连接密码
        });

        console.log("==========打包开始============");

        await Promise.all([
            execPromise(
                "cd d: && cd "+commPath+" && mvn clean package"
            ),
        ]);
        console.log('打包耗时', (Date.now() - start)/1000, 's');

        console.log("==========打包完成============");

        console.log("==========杀死原有进程============");
        const jpsOutput = await ssh.execCommand("lsof -i :8888 -t");
        var pid=jpsOutput.stdout
        console.log("==========原有进程id============");
        console.log(pid);
        await ssh.execCommand(`kill -9 ${pid}`);

        console.log("==========开始上传打包文件============");
        await Promise.all([
            ssh.putFile(
                commPath+"/lq-admin/target/object.jar",
                "/java/object.jar"
            ),
        ]);
        console.log("==========上传完成============");

        console.log("==========开始进行后端部署============");
        await ssh.execCommand(
            "cd /java && nohup java -jar  -Xms512m -Xmx1g -Xmn256m -XX:MaxGCPauseMillis=100  /java/object.jar >object.log &"
        );

        console.log("==========后端部署完成============");

        notify({
            title: "发布成功",
            message: "项目发布成功",
            //  icon: path.join(__dirname, "11.jpg"),
            sound: true, // 播放提示音
            wait: false, // 用户点击通知时才消失
        });

        const end = Date.now();
        console.log("总耗时:", (end - start) / 1000, "s");
    } catch (err) {
        console.log("错误信息", err);
    } finally {
        ssh.dispose();
    }
}

deployProject();
